import {
  setToken
} from "../../utils/auth"
import {
  showModalAsync
} from "../../utils/modal"

const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    username: "",
    pwd: ""
  },

  request(code) {
    wx.request({
      url: app.globalData.requestUrl + "/canteen/login",
      method: "POST",
      data: {
        code: code
      },
      header: {
        'content-type': 'application/json'
      },
      success: (res) => {
        console.log(res.data);
        if (res.data.code == 200) {
          setToken(res.data.token)
          wx.reLaunch({
            url: '/pages/index/index',
          })
        } else {
          console.log(res);
          // 获取 token 失败
          wx.showModal({
            title: '登录失败',
            content: '查看后台日志',
          })
        }
      },
      fail: err => {
        console.log("请求失败", err);
      }
    })
  },

  // 微信登录
  weixinLogin() {
    showModalAsync("正在登录").then(() => {
      console.log("登录...");
      wx.login({
        success: (res) => {
          if (res.code) {
            //发起网络请求
            this.request(res.code)
          } else {
            console.log('登录失败！' + res.errMsg)
          }
        },
        fail: (err) => {
          console.error("登录失败", err);
        }
      })
    });
  }
})